package com.mxz.common.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * List数据递归转换树形结构工具类
 */
public class TreeUtils {
    /**
     * parentId为当前List最上层父id
     * idKey为实体类对象中id键名
     * parentKey为实体类对象中id的键名
     * childName为返回数据子列表的命名
     * removeKey 返回需要删除的key
     */
    public static JSONArray forObjectToTreeMap(List<?> treeList, Long parentId,
                                               String idKey, String parentIdKey, String childName, String removeKey) {
        JSONArray childMenu = new JSONArray();
        for (Object object : treeList) {
            JSONObject jsonMenu = (JSONObject) JSON.toJSON(object);
            Long id = jsonMenu.getLong(idKey);
            Long pid = jsonMenu.getLong(parentIdKey);
            if (parentId.equals(pid)) {
                JSONArray array = forObjectToTreeMap(treeList, id, idKey, parentIdKey, childName,removeKey);
                if (StringUtils.isEmpty(array)) {
                    jsonMenu.remove(childName);
                }else{
                    jsonMenu.put(childName, array);
                }
                if(StringUtils.isNotEmpty(removeKey)){
                    jsonMenu.remove(removeKey);
                }
                childMenu.add(jsonMenu);
            }
        }
        return childMenu;
    }
}
